//
//  MainViewController.m
//  小汽车
//
//  Created by 杜远洋 on 14-12-29.
//  Copyright (c) 2014年 蓝欧科技. All rights reserved.
//






#import "MainViewController.h"
#import "UIImageView+WebCache.h"
#import "AdvertisingModel.h"
#import "AdvertisingDetailViewController.h"
#import "CustomSearchView.h"
#import <MessageUI/MessageUI.h>
#import "AFNetworking.h"
#define KCellIdentifier @"identifier"
#import "ShowImageCell.h"
#import "CircleLayout.h"
#import "Masonry.h"
@interface MainViewController ()<customSearchViewDelegate,UIScrollViewDelegate>
@property(nonatomic,retain) NSTimer *timer;

@end

@implementation MainViewController
-(void)dealloc{
  

    [_bigArray release];
    [_lableTitle release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.bigArray = [NSMutableArray array];
        self.labelArray = [NSMutableArray array];
    }return self;                                     
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self myConnection];
    [self createSearch];
    [self createCollectionView];
    self.navigationItem.title = @"首页";
}
//夜间模式 改变背景颜色
- (void)changeBackgroundColor
{
    NSUserDefaults *myNight = [NSUserDefaults standardUserDefaults];
    if ([[myNight objectForKey:@"night"] isEqualToString:@"0"]) {
         [self.view setBackgroundColor:[UIColor whiteColor]];
        
    }
    else
    {
        [self.view setBackgroundColor:[UIColor colorWithRed:54/255.0f green:54/255.0f blue:54/255.0f alpha:1]];
    }
    
}



- (void)createCollectionView
{
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    CircleLayout *flow = [[CircleLayout alloc] init];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0.0f, height/18, width, height)collectionViewLayout:flow];
    [self.collectionView registerClass:[ShowImageCell class] forCellWithReuseIdentifier:KCellIdentifier];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = YES;
    
    self.collectionView.dataSource = self;
    
    [self.view addSubview:self.collectionView];
    
    //创建label 显示title
    self.lableTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, self.view.frame.size.width, self.view.frame.size.width/18)];
    _lableTitle.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_lableTitle];
    [self.collectionView release];
    [self.lableTitle release];
    
    
    
}




- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_bigArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShowImageCell *cell = (ShowImageCell *)[cView dequeueReusableCellWithReuseIdentifier:KCellIdentifier forIndexPath:indexPath];
    if (!cell) {
        return nil;
    }
    
    [self.view addSubview:self.collectionView];  //？？？？
    AdvertisingModel *model = [_bigArray objectAtIndex:indexPath.row];
    NSLog(@"%ld",(long)indexPath.row);
    
    [cell.imageView setImageWithURL:[NSURL URLWithString:model.imgURL] placeholderImage:[UIImage imageNamed:@"placeHolder.png"] options:SDWebImageRetryFailed];
    NSLog(@"%@",model.imgURL);
    
    //在CollectionViewCell界面显示雪花
    [self snow];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    AdvertisingModel *model = [_bigArray objectAtIndex:indexPath.row];
    AdvertisingDetailViewController *detail = [[AdvertisingDetailViewController alloc] init];
    UINavigationController *na = [[UINavigationController alloc]initWithRootViewController:detail];
    detail.webSite = model.newsLink;
    detail.webTitle = model.title;
    [self presentViewController:na animated:YES completion:nil];
}

//数据解析
- (void)myConnection{
    NSString *str = [NSString stringWithFormat:@"http://wap.xcar.com.cn/cms/interface/5.0/getFocusImg.php?ver=5.3.4"];
     [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        
        NSArray *array = [JSON objectForKey:@"focusImgs"];
        for (NSDictionary *dic in array) {
            AdvertisingModel *model = [[AdvertisingModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_bigArray addObject:model];
            //将所需要的label的数据放到数组里
            
            [self.labelArray addObject:model.title];
        }
        //数组解析时给label附上初始值
        [self.lableTitle setText:[self.labelArray firstObject]];
        [self.lableTitle setTextAlignment:NSTextAlignmentCenter];
        [self.lableTitle setTextColor: [UIColor colorWithRed:17/255.0f green:190/255.0f blue:227/255.0f alpha:1]];
        
        //解析数据的时候  多添加第一张 实现无限循环滚动 噢耶
        
        AdvertisingModel *model = [self.labelArray firstObject];
        [self.labelArray addObject:model];
        
        
        [self.collectionView reloadData];
        //调用定时器
        [self addTimer];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"数据连接失败");
        NSLog(@"%@",error);
    }];
    [operation start];
    [self.lableTitle release];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //滚动的时候label的text跟着改变
    self.lableTitle.text = @"";
    [self.lableTitle removeFromSuperview];
    int i = scrollView.contentOffset.x/self.view.frame.size.width;
    [self.lableTitle setText:[self.labelArray objectAtIndex:i]];
    [self.lableTitle setTextAlignment:NSTextAlignmentCenter];
    [self.lableTitle setTextColor: [UIColor colorWithRed:17/255.0f green:190/255.0f blue:227/255.0f alpha:1]];
    [self.view addSubview:self.lableTitle];
    //获取滚动的当前页  用于定时器滚动到下一页
   


}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.currentPage = (CGFloat)(scrollView.contentOffset.x + self.view.frame.size.width / 2)/ self.view.frame.size.width;
    NSLog(@"scrollView =  %lf",scrollView.contentOffset.x);
    
    if (scrollView.contentOffset.x >= self.view.frame.size.width * [self.bigArray count]) {
        [self.collectionView setContentOffset:CGPointMake(0, 0) animated:NO];
        NSLog(@"yesh1!!!!!!!!!!");
        return;
    }
    

    if (scrollView.contentOffset.x >= 0 && [self.labelArray count] != 0 && self.timer) {
        self.lableTitle.text = @"";
        [self.lableTitle removeFromSuperview];
        NSInteger i = (NSInteger)(self.collectionView.contentOffset.x / self.view.frame.size.width);
        [self.lableTitle setText:[self.labelArray objectAtIndex:i]];
        [self.lableTitle setTextAlignment:NSTextAlignmentCenter];
        [self.lableTitle setTextColor: [UIColor colorWithRed:17/255.0f green:190/255.0f blue:227/255.0f alpha:1]];
        [self.view addSubview:self.lableTitle];

    }
  
    //利用间隔时间 实现页面的切换
    
   

}
//无限循环滚动

- (void)nextPage
{
    NSInteger page = self.currentPage;
    if (page == 4) {
        page = 5;
        
    }
    else
    {
        page ++;
    }
    
    //根据page让它滚动
   
    CGFloat x = page * self.view.frame.size.width;
    [self.collectionView setContentOffset:CGPointMake(x, 0) animated:YES];
    NSLog(@"collection =  %lf",self.collectionView.contentOffset.x);
    
}
//设置定时器
- (void)addTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //开始拖拽的时候 移除计时器
    [self removeTimer];
}

- (void)removeTimer
{
    //移除计时器
    [self.timer invalidate];
}
-(void)createMusicView{
    
}

//雪花函数
-(void)snow
{
    _imagesArray = [[NSMutableArray alloc] init];
    //每一轮出现雪花的数目
    for (int i = 0; i < 21; ++ i) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snow"]];
      //  随机雪花出现的大小,起始y
        float y = arc4random()%20 + 10;
        imageView.frame = CGRectMake(arc4random()%(int)self.view.frame.size.width, -y, y, y);
        //随机雪花的透明度
        imageView.alpha =  ((float)(arc4random()%10))/10;
        [self.view addSubview:imageView];
        [_imagesArray addObject:imageView];
    }
    //雪花产生的时间,调用产生的方法
    [NSTimer scheduledTimerWithTimeInterval:1.1 target:self selector:@selector(makeSnow) userInfo:nil repeats:YES];
  
}

static int i = 0;
- (void)makeSnow
{
    i = i + 1;
    if ([_imagesArray count] > 0) {
        UIImageView *imageView = [_imagesArray objectAtIndex:0];
        imageView.tag = i;
        [_imagesArray removeObjectAtIndex:0];
        //动画开始时出现那个雪花
        [UIView beginAnimations:[NSString stringWithFormat:@"%li",(long)imageView.tag] context:nil];
        //随机雪花飘落的时间
        CGFloat time= (random()%100)/10+5;
        [UIView setAnimationDuration:time];
        
        [UIView setAnimationDelegate:self];
        //随机雪花消逝的高度
        imageView.frame = CGRectMake(imageView.frame.origin.x,arc4random()%(int)self.view.frame.size.height, imageView.frame.size.width, imageView.frame.size.height);
        [UIView commitAnimations];
    
    }
    
}



- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    UIImageView *imageView = (UIImageView *)[self.view viewWithTag:[animationID intValue]];
    float x = arc4random()%30 + 10;
    imageView.frame = CGRectMake(arc4random()%(int)self.view.frame.size.width, -x, x, x);
    [_imagesArray addObject:imageView];
}




-(void)createSearch{

    CustomSearchView *customSearch = [[CustomSearchView alloc]initWithFrame:CGRectMake(320, 0, 44, 44)];
    customSearch.delegate = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
    view.backgroundColor = [UIColor colorWithRed:17.0/255.0 green:190.0/255.0 blue:227.0/255.0 alpha:1.0];
    [self.navigationController.view addSubview:view] ;
    [view addSubview:customSearch];
   
}

-(CGRect)destinationFrameForSearchBar:(CustomSearchView *)searchBar{
    
    return CGRectMake(5, 0, CGRectGetWidth(self.view.bounds)-10, 44); 
}

-(void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
    //选择范围
}
-(void)buttonAction:(id)sender{
    AdvertisingDetailViewController *detail = [[AdvertisingDetailViewController alloc]init];
    UIButton *button = (UIButton *)sender;
    AdvertisingModel *model = [_bigArray objectAtIndex:button.tag-1];
    detail.webTitle = model.title;
    detail.webSite = model.newsLink;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self changeBackgroundColor];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
